package com.wanlian.router.ui;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.wanlian.router.BuildConfig;
import com.wanlian.router.GlobalInfo;
import com.wanlian.router.MainActivity;
import com.wanlian.router.R;
import com.wanlian.router.app.AppConfig;
import com.wanlian.router.bean.Config;
import com.wanlian.router.bean.User;
import com.wanlian.router.bean.VersionInfo;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.internal.INetCallBack;
import com.wanlian.router.net.netty.SocketService;
import com.wanlian.router.storage.AppData;
import com.wanlian.router.ui.dialog.UpgradeDialog;
import com.wanlian.router.ui.dialog.UpgradeDownDialog;
import com.wanlian.router.ui.login.LoginActivity;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Locale;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by Hyu on 2018/9/5.
 * Email: fvaryu@qq.com
 */

@RuntimePermissions
public class SplashActivity extends WlBaseActivity implements UpgradeDialog.OnUpgradeClickListener {

    private static final int DESTROY = 101;
    private String APP_NAME;
    private String apkUrl;
    private VersionInfo mVersionInfo;


    @Override
    public void onBackPressed() {
        // 屏蔽掉启动时按back键
    }

    @Override
    public void initUI() {
        super.initUI();
        APP_NAME = this.getResources().getString(R.string.app_name);

    }

    @Override
    public void initData() {
        super.initData();

        SplashActivityPermissionsDispatcher.readDeviceIdWithPermissionCheck(this);
    }

    @Override
    protected int layout() {
        return R.layout.activity_splash;
    }

    // 必备权限 全部请求到后会调用此处
    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void storage() {

        startService(new Intent(this, SocketService.class));

        NetWorkingClient.getInstance().queryConfig(getActivity(), false, new INetCallBack<List<Config>>() {
            @Override
            public void onFinish(ResponseData response, @Nullable List<Config> configs) {
                if (response.isSuccess()) {
                    if (configs != null) {
                        String versionInfo = null;
                        for (Config config : configs) {
                            if(TextUtils.isEmpty(config.getCkey()) || TextUtils.isEmpty(config.getCvalue())) {
                                continue;
                            }
                            if (AppConfig.APP_VERSION_ANDROID.equals(config.getCkey())) {
                                versionInfo = config.getCvalue().trim();
                            }
                            AppData.DEFAULT.put(config.getCkey().trim(), config.getCvalue().trim());
                        }


                        try {
                            mVersionInfo = new Gson().fromJson(versionInfo, VersionInfo.class);
                            if (!BuildConfig.VERSION_NAME.equals(mVersionInfo.getVersionCode())
                                    && !TextUtils.isEmpty(AppData.DEFAULT.getIgnoreVersion())
                                    && !AppData.DEFAULT.getIgnoreVersion().equals(mVersionInfo.getVersionCode())
                                    ) {
                                UpgradeDialog dialog =new UpgradeDialog(getActivity());
                                apkUrl = mVersionInfo.getDownUrl();
                                dialog.setForceUpdate("true".equals(mVersionInfo.getIsForceUpdata()));
                                dialog.setOnUpgradeClickListener(SplashActivity.this);
                                dialog.setUpgradeLog(mVersionInfo.getUpdateLog().replace(";", "\n"));
                                dialog.show();
                            }else {
                                toNext();
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }


                    }else {
                        toNext();
                    }
                }else {
                    toNext();
                }
            }
        });
    }

    @Override
    public void onUpgradeClick(Dialog dialog, int which) {

        if (which == 0) {
            dialog.dismiss();
            if (mVersionInfo != null) {
                AppData.DEFAULT.setIgnoreVersion(mVersionInfo.getVersionCode());
            }
            toNext();
        }else {
            if (TextUtils.isEmpty(apkUrl) || !apkUrl.endsWith(".apk")) {
                showToast("无效下载地址:" + apkUrl);
                return;
            }
            UpgradeDownDialog upgradeDownDialog = new UpgradeDownDialog(this);
            upgradeDownDialog.show();
            upgradeDownDialog.start(apkUrl);
        }
    }

    private void toNext() {



        if (GlobalInfo.getInstance().isLogin()) {

            NetWorkingClient.getInstance().userInfo(getActivity(), new INetCallBack<User>() {
                @Override
                public void onFinish(ResponseData response, @Nullable User user) {
                    if (response.isSuccess()) {
                        GlobalInfo.getInstance().setUser(user);

                    }else {
                        showToast(response.getMessage());
                        GlobalInfo.getInstance().getUserData().clean();
                    }
                    new WeakHandler(SplashActivity.this).sendEmptyMessageDelayed(DESTROY, 500);
                }
            });
        }else {
            new WeakHandler(SplashActivity.this).sendEmptyMessageDelayed(DESTROY, 2000);
        }
    }


    void ask() {
        new AlertDialog.Builder(this)
                .setTitle("权限申请")
                .setMessage(String.format(Locale.getDefault(), "%s使用电话权限确定本机号码和设备ID,以保证账号登录的安全性。%s不会拨打其他号码或终止通话。" +
                        "\n请在设置-应用-%s-权限中开启电话权限，已正常使用%s。", APP_NAME, APP_NAME, APP_NAME, APP_NAME))
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).setPositiveButton("去设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                try {
                    Intent i = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + BuildConfig.APPLICATION_ID));
                    startActivity(i);
                } catch (Exception e) {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
                    startActivity(intent);
                }
                finish();
            }
        }).setCancelable(false).create().show();
    }

    @NeedsPermission(Manifest.permission.READ_PHONE_STATE)
    void readDeviceId() {
        SplashActivityPermissionsDispatcher.storageWithPermissionCheck(this);
    }

    @OnNeverAskAgain(Manifest.permission.READ_PHONE_STATE)
    void onNeverAskAgainReadPhone() {
        ask();
    }

    @OnPermissionDenied(Manifest.permission.READ_PHONE_STATE)
    void onDeniedForReadPhone() {
        ask();
    }

    @OnShowRationale(Manifest.permission.READ_PHONE_STATE)
    void showRationaleForReadPhone(final PermissionRequest request) {
        permissionWarn(String.format("%s使用电话权限确定本机号码和设备ID,以保证账号登录的安全性。%s不会拨打其他号码或终止通话。" +
                "\n请在设置-应用-%s-权限中开启电话权限，已正常使用%s。", APP_NAME, APP_NAME, APP_NAME, APP_NAME));
    }

    void askStorage() {
        permissionWarn(String.format("%s使用存储权限，以存储用户数据。%s不会恶意修改、删除设备上的数据文件。" +
                "\n请在设置-应用-%s-权限中开启电话权限，已正常使用%s。", APP_NAME, APP_NAME, APP_NAME, APP_NAME));
    }

    private void permissionWarn(String message) {
        new AlertDialog.Builder(this)
                .setTitle("权限申请")
                .setMessage(message)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).setPositiveButton("去设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_MANAGE_ALL_APPLICATIONS_SETTINGS);
                startActivity(intent);
                finish();
            }
        }).setCancelable(false).create().show();
    }

    @OnNeverAskAgain(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void onNeverAskAgainStorage() {
        askStorage();
    }

    @OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void onDeniedForStorage() {
        askStorage();
    }

    @OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showRationaleForStorage(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setTitle("权限申请")
                .setMessage(String.format("%s使用存储权限，以存储用户数据。%s不会恶意修改、删除设备上的数据文件。" +
                        "\n请在设置-应用-%s-权限中开启电话权限，已正常使用%s。", APP_NAME, APP_NAME, APP_NAME, APP_NAME))
                .setNegativeButton(R.string.button_deny, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        request.cancel();
                    }
                }).setPositiveButton(R.string.button_allow, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                request.proceed();
            }
        }).setCancelable(false).create().show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SplashActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }




    private static class WeakHandler extends Handler {
        WeakReference<SplashActivity> mWeakReference;

        WeakHandler(SplashActivity activity) {
            mWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == DESTROY) {
                if (mWeakReference.get() != null) {
                    if (GlobalInfo.getInstance().isLogin()) {

                        mWeakReference.get().redirectActivity(MainActivity.class);
                    } else {
                        mWeakReference.get().redirectActivity(LoginActivity.class);
                    }

                    mWeakReference.get().finish();
                    mWeakReference = null;
                }
            }
        }
    }


}
